<template>
  <a-row :gutter="16" style="display: flex; justify-content: flex-end">
    <a-button type="primary" @click="goBack()">返回上一级</a-button>
  </a-row>
  <div>
    <a-table :columns="columns" :dataSource="data" :pagination="false" />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, h, computed, onBeforeUpdate } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Table } from 'ant-design-vue'
import DataConstant from '@/DataConstant'

export default defineComponent({
  components: {
    ATable: Table
  },

  setup() {
    const route = useRoute()
    const router = useRouter()
    const currentPathSegment = ref('') // 当前路径段
    const segments = ref<string[]>([]) // 路径段数组

    // 在组件挂载时获取当前路径的最后一个部分
    onMounted(() => {
      const pathSegments = route.path.split('/').filter(Boolean)
      segments.value = pathSegments
      console.log('onBeforeUpdate' + pathSegments)
      currentPathSegment.value = pathSegments[pathSegments.length - 1] || ''
    })

    // 在路由更新前获取数据
    onBeforeUpdate(() => {
      const pathSegments = route.path.split('/').filter(Boolean)
      segments.value = pathSegments

      currentPathSegment.value = pathSegments[pathSegments.length - 1] || ''
    })
    const goBack = () => {
      router.go(-1)
    }

    // 根据 segments 的值动态获取 DataConstant 中的数据
    const data = computed(() => {
      const getArrayByKey = (obj: any[], targetKey: String) => {
        for (const item of obj) {
          if (item.key === targetKey) {
            return item.value
          }
        }
        return null
      }

      const arrayValue = getArrayByKey(DataConstant, segments.value.join('/'))
      return arrayValue || []
    })

    return {
      currentPathSegment,
      segments,
      data, // 导出 data 以便在模板中使用
      goBack
    }
  },

  data() {
    return {
      columns: [
        { title: '风险点', dataIndex: 'riskPoint', key: '风险点' },
        {
          title: '危害描述',
          dataIndex: 'hazardDescription',
          key: '危害描述',
          customRender: ({ text }: { text: string }) =>
            h(
              'ul',
              { style: { paddingLeft: '20px' } },
              text.split('\n').map((item, index) => h('li', { key: index }, item))
            )
        },
        { title: '后果', dataIndex: 'consequence', key: '后果' },
        { title: '后果的严重程度', dataIndex: 'severityOfConsequence', key: '后果的严重程度' },
        { title: '风险等级', dataIndex: 'riskLevel', key: '风险等级' }
      ]
    }
  }
})
</script>
